package com.bilubi.reggie.reggie.service.Impl;

import com.bilubi.reggie.reggie.bean.ShoppingCart;
import com.bilubi.reggie.reggie.bean.User;
import com.bilubi.reggie.reggie.mapper.ShoppingCartMapper;
import com.bilubi.reggie.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<ShoppingCart> selectShoppingCartByUserId(Long userId) {
        return shoppingCartMapper.selectByUserId(userId);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public ShoppingCart addShoppingCart(ShoppingCart shoppingCart) {
        // 直接更新相关数据number
        ShoppingCart row = shoppingCartMapper.selectByUserIdAndItemId(shoppingCart);
        if (row != null){
            // 查询结果不为空，表明购物车中有,更新后返回数据
            row.setNumber(row.getNumber() + 1);
            shoppingCartMapper.updateByUserIdAndItemId(row);
            return shoppingCartMapper.selectByUserIdAndItemId(row);
        }
        else {
            // 影响行数为0，表明购物车中无此数据，新增一条数据
            Date date = new Date();
            shoppingCart.setCreateTime(date);
            shoppingCartMapper.insertSelective(shoppingCart);
            return shoppingCartMapper.selectByUserIdAndItemId(shoppingCart);
        }
    }

    @Override
    public int cleanShoppingCart() {
        return shoppingCartMapper.deleteByUserId(new ShoppingCart());
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public ShoppingCart subShoppingCart(ShoppingCart shoppingCart) {
        ShoppingCart row = shoppingCartMapper.selectByUserIdAndItemId(shoppingCart);
        if (row != null){
            if (row.getNumber() == 1){
                shoppingCartMapper.deleteByUserItemId(shoppingCart);
                row.setNumber(0);
                return row;
            }
            else {
                row.setNumber(row.getNumber() - 1);
                shoppingCartMapper.updateByUserIdAndItemId(row);
            }
        }
        return shoppingCartMapper.selectByUserIdAndItemId(row);
    }
}
